package com.yrh.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
    private  static DataSource ds=null;
    //获取druid连接池信息
    static {
        try {
            InputStream is = ClassLoader.getSystemResourceAsStream("druid.properties");
            Properties pp=new Properties();
            pp.load(is);
            is.close();
          ds= DruidDataSourceFactory.createDataSource(pp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取数据库连接池对象
    public static DataSource getDataSource(){
        return ds;
    }
    /*
    获取到连接对象
    * */
    public static Connection getConnection(){
        Connection coon=null;
        try {
            //防止空值正异常
            if (ds!=null){
                coon=ds.getConnection();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return coon;
    }
    /*释放资源*/
    public static void close(Connection coon, Statement stat){
        close(coon,stat,null);
    }
    public static void close(Connection coon, Statement stat, ResultSet resu){
        if (resu!=null){
            try {
                resu.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat!=null){
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (coon!=null){
            try {
                coon.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
